//
//  AppCoordinator.swift
//  Progress
//
//  Created by bin hu on 2025/6/30.
//

import Foundation

// MARK: - 使用示例
class AppCoordinator {
    func setup() {
        // 1. 初始化域名配置
        DynamicDomainManager.shared.fetchInitialConfig { result in
            switch result {
            case .success:
                // 2. 连接Socket
                SocketConnectionManager.shared.connect()
                
                // 3. 添加Socket监听
                self.setupSocketListeners()
                
                // 4. 加载初始数据
                self.loadInitialData()
                
            case .failure:
                // 处理配置加载失败
                self.showConfigError()
            }
        }
        
        // 监听Socket连接状态
        SocketConnectionManager.shared.connectionStatusChanged = { [weak self] connected in
            self?.updateConnectionStatus(connected)
        }
    }
    
    private func setupSocketListeners() {
        // 添加消息监听
        SocketConnectionManager.shared.addListener(for: "newMessage") { payload in
            print("Received new message: \(payload)")
            // 更新UI...
        }
        
        // 添加通知监听
        SocketConnectionManager.shared.addListener(for: "notification") { payload in
            print("Received notification: \(payload)")
            // 显示通知...
        }
    }
    
    private func loadInitialData() {
        // 加载用户资料
        APIService.shared.request("/user/profile") { (result: Result<UserProfile, APIError>) in
            switch result {
            case .success(let profile):
                print("Loaded user profile: \(profile)")
                // 更新UI...
                
            case .failure(let error):
                print("Failed to load profile: \(error)")
                // 显示错误...
            }
        }
        
        // 加载消息列表
        APIService.shared.request("/messages") { (result: Result<[Message], APIError>) in
            // 处理结果...
        }
    }
    
    private func updateConnectionStatus(_ connected: Bool) {
        DispatchQueue.main.async {
            // 更新UI显示连接状态
            let statusText = connected ? "已连接" : "连接中..."
            // statusLabel.text = statusText
            log(statusText)
        }
    }
    
    private func showConfigError() {
        // 显示配置错误提示
        DispatchQueue.main.async {
            // alertController.show(...)
            log("some thing error")
        }
    }
}

// MARK: - 示例模型
struct UserProfile: Codable {
    let id: String
    let name: String
    let email: String
}

struct Message: Codable {
    let id: String
    let content: String
    let timestamp: Date
}
